define(function(require, exports) {
	var $ = require('jquery');
	var pubjs = require('pubjs');
	var util = require('util');
	var view  = require('@base/view');
	var menu = require('@base/common/menu');
	var common = require('modules/common');

	var SERVER_OPTITIONS =  [
		{
			id: 0,
			name: LANG('自动选择最新服务器')
		},
		{
			id: -1,
			name: LANG('导入上次登录的服务器')
		}
	];
	var SERVER_OPTITIONS_MAP = (function(options) {
		var map = {};
		util.each(options, function(item) {
			map[item.id] = item.name;
		});
		return map;
	})(SERVER_OPTITIONS);

	// 添加产品
	var Base = view.container.extend({
		init: function(config) {
			var self = this;
			var userData = pubjs.getUser();

			config = pubjs.conf(config, {
				 'class': 'M-PageGameForm'
				 // 活动类型 1 RTB 2代理 3直投，4移动
				 ,'channelType': 1
				 ,'tplFile': '/tpl/campaign/modules/gameForm.tpl'
				 ,'limit': 0             // <Number> 可选产品数量，0为不限制
				 ,'sweety_limit': 0      // <NUmber> 创意包数量限制
				 ,'view_model': {
					// 广告形式 [1: 硬广，2弹窗]
					'_adType': 0
					// 是否已和DSP对接
					,'_isButt': userData && userData.campany && userData.campany.IsButt
					// 显示选择产品按钮
					,'_showSelectBtn': true
					// 服务器select的文字描述
					,'_serverTextMap': SERVER_OPTITIONS_MAP
					// 产品列表
					,'products': []
					// 添加产品按钮点击
					,evAddBtnClick: self.eventAddBtnClick
					// 选择产品服务器点击事件
					,evColSelectServerClick: self.eventColSelectServerClick
					// 移除产品按钮点击
					,evColRemoveClick: self.eventColRemoveClick
					// 编辑产品策略
					,evColEditRuleClick: self.eventColEditRuleClick
					// 图片错误回调
					,evImageError: common.onImageError
				 }
			});

			self.Super('init', arguments);
		}
		,afterBuild: function() {
			var c = this.getConfig();
			this.createAsync('selectPopwin', 'product/popwin/product.base', {
				'limit': c.limit
			});
			this.createAsync('detail', 'campaign/modules/creativeDetail.popwin', {
				channelType: c.channelType,
				sweety_limit: c.sweety_limit
			});

			this.buildFromTemplate();
		}
		,afterBuildTemplate: function() {}
		,reset: function() {
			// 渠道id
			this.$exchangeId = 0;
			this.vm.reset();
			return this;
		}
		,getData: function() {
			var data = [];
			var self = this;
			var vm = self.vm;
			var isButt = vm.getItem("_isButt");
			var ratios = self.$.sectionRatio.getData();

			util.each(vm.getItem("products"), function(product) {
				data.push({
					_id: product._id,
					ServerId: isButt ? product.serverId : null,
					RatioSet: ratios[product._id],
					Sweetys: self.transformList(product.sweeties),
					WhiskyCreatives: self.transformList(product.whiskies),
					SweetyRatioType: product.sweetyOptimizaType,
					WhiskyCreativeRatioType: product.whiskyOptimizaType
				});
			});

			return data;
		}
		,setData: function(data) {
			var self = this;
			self.vm.$.products = [];
			util.each(data, function(item) {
				self.addItem(item);
			});
		}
		,transformList: function(list){
			var new_list = [];
			util.each(list, function(item){
				var new_item = {
					_id: item._id,
					RatioSet: item.RatioSet
				};
				if (item.WhiskyIds){
					new_item.WhiskyIds = item.WhiskyIds;
				}
				new_list.push(new_item);
			});
			return new_list;
		}
		// 新增产品
		,addItem: function(data) {
			var vm = this.vm.$;
			var limit = this.getConfig('limit');
			var products = this.vm.$.products;

			var item = {
					_id: data._id,
					thumb: data.Cover,
					name: data.Name,
					desc: data.Description,
					serverId: data.ServerId || SERVER_OPTITIONS[0].id,
					sweeties: data.Sweetys || [],
					whiskies: data.WhiskyCreatives || [],
					sweetyOptimizaType: data.SweetyRatioType,
					whiskyOptimizaType: data.WhiskyCreativeRatioType
			};

			if (!util.exist(products.$model, item._id, '_id')) {
				if (limit > 0 && products.length >= limit){
					vm._showSelectBtn = false;
					return pubjs.alert(LANG('暂时只允许选择 %1 个游戏', limit));
				}
				products.push(item);
				this.$.sectionRatio.add({
					id: item._id,
					text: item.name
				});
			}
		}
		// 移除产品
		,removeItem: function(id) {
			util.remove(this.vm.$.products, id, '_id');
			this.vm.$._showSelectBtn = true;
			this.send(this.$.selectPopwin, 'removeItem', {id: id});
			this.$.sectionRatio.remove(id);
		}
		// 编辑产品
		,editItem: function(item, field, newValue) {
			if (field in item) {
				item[field] = newValue;
			}
		}
		// 添加产品按钮点击
		,eventAddBtnClick: function() {
			var data = this.vm.getItem("products");
			this.$.selectPopwin.setValue(data).reload().show();
		}
		// 选择产品服务器按钮点击
		,eventColSelectServerClick: function(el, item) {
			var mod = this.create('menu', menu.base, {
				trigger: el,
				relate_elm: el,
				width: $(el).outerWidth(),
				options: SERVER_OPTITIONS
			});

			this.$openMenu = {
				data: item,
				mod: mod
			};
		}
		// 选择产品服务器menu选中消息
		,onMenuSelected: function(ev) {
			var param = ev.param.shift();
			var cache = this.$openMenu;

			if (cache && cache.mod == ev.source) {
				cache.mod.destroy();
				this.editItem(cache.data, 'serverId', param.data.id);
			}
		}
		// 移除产品按钮点击
		,eventColRemoveClick: function(id) {
			this.removeItem(id);
		}
		// 编辑产品策略
		,eventColEditRuleClick: function(item) {
			this.$.detail.reset().show().setData(item.$model);
		}
		// 广告形式更改消息, 广告形式改变时广播
		,onAdTypeChange: function(ev) {
			this.vm.$._adType = ev.param;
		}
		// 渠道更改消息, 渠道变更时广播
		,onExchangeIdChange: function(ev) {
			this.$exchangeId = ev.param;
		}
		// 编辑创意包与落地页完成消息
		,onCreativeDetailDone: function(ev) {
			var data = ev.param;
			var item = util.find(this.vm.$.products, data._id, '_id');

			if (item) {
				item.sweeties = data.sweeties;
				item.whiskies = data.whiskies;
				item.sweetyOptimizaType = data.sweetyOptimizaType;
				item.whiskyOptimizaType = data.whiskyOptimizaType;
			}
			return false;
		}
		// 选择产品
		,onSelectProduct: function(ev) {
			this.addItem(ev.param.data);
		}
		// 取消选择产品
		,onUnselectProduct: function(ev) {
			this.removeItem(ev.param.id);
		}
	});

	exports.base = Base;
});